package com.example.rocketmq.message;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author Administrator
 * @version 1.0
 **/
@Component
public class ProducerSimple {

    @Autowired
    RocketMQTemplate rocketMQTemplate;

    public static void main(String[] args) throws Exception {
        DefaultMQProducer producer = new DefaultMQProducer();
        producer.setNamesrvAddr("101.35.153.254:9876;121.5.23.139:9876;1.15.1.55:9876");
        producer.setProducerGroup("groupA");
        producer.start();
        for (int i = 0; i < 10; i++) {
            org.apache.rocketmq.common.message.Message message = new org.apache.rocketmq.common.message.Message();
            message.setTopic("topicA");
            message.setTags("tagsA");
            message.setBody(("消息A"+i).getBytes());
            SendResult sendResult = producer.send(message);
            System.out.println(sendResult);
        }

        producer.shutdown();
    }


    /**
     * 发送同步消息
     * @param topic 主题
     * @param msg 消息内容
     */
    public void sendSyncMsg(String topic,String msg){
        SendResult sendResult = rocketMQTemplate.syncSend(topic, msg);
        System.out.println("");
    }

    /**
     * 异步消息
     * @param topic
     * @param msg
     */
    public void sendASyncMsg(String topic,String msg){
        rocketMQTemplate.asyncSend(topic, msg, new SendCallback() {

            //消息发送成功的回调
            @Override
            public void onSuccess(SendResult sendResult) {
                System.out.println(sendResult);
            }

            //消息发送失败的回调
            @Override
            public void onException(Throwable throwable) {
                System.out.println(throwable.getMessage());
            }
        });
    }

}
